package dao;

import util.IRowMapper;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import static util.Iconstants.*;

/**
 * Created by Administrator on 2017/11/9.
 */
public class DBHelper<T> {
    private Connection conn;
    private PreparedStatement ps;
    private ResultSet rs;
    static{
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //打开连接
    private void openConnection()throws SQLException {
        if(conn==null||conn.isClosed()){
            conn= DriverManager.getConnection(URL,USERNAME,PWD);
        }
    }
    //设置占位符
    public void setParas(Object ...paras)throws SQLException{
        if(paras!=null&&paras.length>0) {
            for(int i=0;i<paras.length;i++) {
                ps.setObject(i+1, paras[i]);
            }
        }
    }
    //增删改辅助方法
    public int executeUpdate(String sql,Object ...paras)throws SQLException,ClassNotFoundException{
        openConnection();
        ps=conn.prepareStatement(sql);
        setParas(paras);
        return ps.executeUpdate();
    }
    //查询辅助方法
    public ResultSet executequery(String sql, Object ...paras)throws SQLException,ClassNotFoundException{
        openConnection();
        ps=conn.prepareStatement(sql);
        setParas(paras);
        return ps.executeQuery();
    }
    //全查辅助方法
    public List<T> queryAllHelper(IRowMapper<T> rowmapper, String sql, Object ...paras)throws SQLException,ClassNotFoundException{
        List<T> list=new ArrayList<T>();
        rs=executequery(sql,paras);
        while(rs.next()){
            T t=rowmapper.mapper(rs);
            list.add(t);
        }
        return list;
    }
    //单查辅助方法
    public Object querySingle(String sql,Object ...paras)throws ClassNotFoundException,SQLException{
        rs=executequery(sql,paras);
        if(rs.next()){
            return rs.getObject(1);
        }
        return null;
    }
    //关闭
    public void close()throws SQLException{
        if(ps!=null)ps.close();
        if(rs!=null)rs.close();
        if(conn!=null&&!conn.isClosed())conn.close();
    }
}
